package com.weibo4terios.ui;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.weibo4terios.R;
import com.weibo4terios.conts.CommonStrs;
import com.weibo4terios.dao.Status;
import com.weibo4terios.logic.MainService;
import com.weibo4terios.logic.Task;
import com.weibo4terios.ui.adapter.WeiboAdapter;
import com.weibo4terios.ui.util.IWeiboActivity;
import com.weibo4terios.ui.util.PullToRefresh;
import com.weibo4terios.ui.util.PullToRefresh.UpdateHandle;

/**
 * HomeActivity.java 2012-10-30 下午4:45:38
 * 
 * @author Wang Tengrui
 */
public class HomeActivity extends Activity implements IWeiboActivity, UpdateHandle, OnGestureListener,OnTouchListener{
	public static final int REFRESH_WEIBO = 1;
	public int nowPage = 1;// 当前第几页
	public int pageSize = CommonStrs.MAX_INFO_NUM;// 每页条数
	private ListView weiboList;// 微博信息显示
	private WeiboAdapter homeAdapter;// 微博信息的适配器
	private GestureDetector mGestureDetector;

	private View login_progressBar;// 开始页菊花

	private PullToRefresh pullToRefresh;

	@SuppressWarnings("static-access")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(getWindow().FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		initview();// 初始化布局
		MainService.allActivity.add(this);
		init();// 开始请求数据
	}

	/**
	 * 初始化布局
	 */
	private void initview() {
		pullToRefresh = (PullToRefresh) this.findViewById(R.id.pullToRefresh);
		pullToRefresh.setUpdateHandle(this);
		mGestureDetector = new GestureDetector(this);
		
		
		weiboList = (ListView) this.findViewById(R.id.weibolist);
		login_progressBar = this.findViewById(R.id.login_progresBar);
		weiboList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Status nowstu = (Status) parent.getAdapter().getItem(position);// 从适配器中获取当前点击项的内容
				Intent intent = new Intent(HomeActivity.this, WeiboInfo.class); // 发送到WeiboInfo
				intent.putExtra("status", nowstu);
				HomeActivity.this.startActivity(intent);
			}
		});
	}

	@Override
	public void init() {
		// 任务参数（当前页面的分页信息）
		HashMap<String, Integer> paramHashMap = new HashMap<String, Integer>();
		paramHashMap.put("nowPage", Integer.valueOf(nowPage));
		paramHashMap.put("pageSize", Integer.valueOf(pageSize));

		// 加载主页微博信息任务
		Task task = new Task(CommonStrs.TASK_GET_USER_HOMETIMEINLINE, paramHashMap);
		MainService.allTask.add(task);
	}

	/**
	 * 刷新主页面信息
	 */
	public void refresh() {
		nowPage = 1;// 将当前页重置为第一页
		init();// 这里就是再次请求第一页信息
	}

	@Override
	public void onUpdate() {
		new PullRefreshThread(handler).start();
	}

	class PullRefreshThread extends Thread {
		private Handler handler;

		public PullRefreshThread(Handler handler) {
			this.handler = handler;
		}

		@Override
		public void run() {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Message msg = handler.obtainMessage();
			handler.sendMessage(msg);
			super.run();
		}
	}

	private final Handler handler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(Message msg) { // 处理Message，更新ListView
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss     ");
			Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
			String str = formatter.format(curDate);
			pullToRefresh.endUpdate(str);
		}
	};

	@SuppressWarnings("unchecked")
	@Override
	public void refresh(Object... param) {
		int flag = ((Integer) param[0]).intValue();// 获取任务标志
		switch (flag) {
		case REFRESH_WEIBO:
			if (nowPage == 1) {
				login_progressBar.setVisibility(View.GONE);// ListView上层的菊花关闭
				List<Status> nowStatus = (List<Status>) param[1];
				homeAdapter = new WeiboAdapter(this, nowStatus);
				weiboList.setAdapter(homeAdapter);
			} else {
				homeAdapter.addmoreDate((List<Status>) param[1]);
			}
			break;
		}

	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return mGestureDetector.onTouchEvent(event);
	}
}
